//    Copyright (C) Kherty.  All rights reserved.
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Media3D;

namespace OpenLS.Chart.UI.Internals
{
    public class Camera3D2DProjector
    {
        private readonly Camera Camera;
        private Size Size;

        public Camera3D2DProjector(Camera camera, Size size)
        {
            Camera = camera;
            Size = size;
        }

        internal Point Point3DToPoint2D(Point3D point3D)
        {
            var pt = new Point();
            if (Camera != null)
            {
                var p4 = new Point4D(point3D.X, point3D.Y, point3D.Z, 1);
                pt = worldToViewport(p4, GetAspectRatio(), new Rect(new Point(), Size));
            }
            return pt;
        }

        private Point worldToViewport(Point4D p, double aspectRatio, Rect rect)
        {
            // double aspectRatio = M3DUtil.GetAspectRatio(this.Viewport.Size);
            if (Camera != null)
            {
                Matrix3D viewMatrix = CameraHelper.GetViewMatrix(Camera);
                Matrix3D projectionMatrix = CameraHelper.GetProjectionMatrix(Camera, aspectRatio);

                Matrix3D matrixd = viewMatrix*projectionMatrix;
                Point4D point = p;
                point *= matrixd;
                var point2 = new Point(point.X/point.W, point.Y/point.W);
                //\\return point2;
                Point point3 = (point2*GetHomogeneousToViewportTransform(rect));
                return point3;
            }
            return new Point(0.0, 0.0);
        }

        internal double GetAspectRatio()
        {
            return (Size.Width/Size.Height);
        }

        internal static Matrix GetHomogeneousToViewportTransform(Rect viewport)
        {
            double num2 = viewport.Width/2.0;
            double num = viewport.Height/2.0;
            double offsetX = viewport.X + num2;
            return new Matrix(num2, 0.0, 0.0, -num, offsetX, viewport.Y + num);
        }
    }
}